package swing;

import net.FileUploader;
import utils.CharUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LoadPicDemo extends JFrame {
    private JButton btnAdd, btnDel, btnUpload;
    private ArrayList<PicBean> mData = new ArrayList<>();//图片对象
    private static final String urlPath = "http://112.74.38.81:8080/oa/Image/upload";

    private static Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();

    public static void main(String[] args) {
        LoadPicDemo frame = new LoadPicDemo();
        frame.setPreferredSize(new Dimension(screen.width / 10 * 6,
                screen.height / 10 * 6));
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public LoadPicDemo() {
        JPanel images = new PicJpanel(new GridLayout(0,6,5,5));
        images.setLayout(new BoxLayout(images , BoxLayout.X_AXIS));
        images.setPreferredSize(new Dimension(0 , 500));


        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setViewportView(images);

        scrollPane.setHorizontalScrollBarPolicy(
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scrollPane.setVerticalScrollBarPolicy(
                JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);

        add(scrollPane, BorderLayout.CENTER);

        JPanel buttons = new JPanel();
        buttons.add(btnAdd = new JButton("add"));
        buttons.add(btnDel = new JButton("del"));
        buttons.add(btnUpload = new JButton("upload"));
        buttons.setBackground(Color.darkGray);

        btnAdd.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser fd = new JFileChooser();
                //fd.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                fd.showOpenDialog(null);
                File f = fd.getSelectedFile();
                if(f != null){
                    String fileName = f.getAbsolutePath();
                    if(CharUtil.chinsesExistence(fileName)){
                        errDialog("文件不可以有中文");
                        return;
                    }
                    if(fileName.endsWith(".jpg") || fileName.endsWith(".png")|| fileName.endsWith(".jif")){
                        ImageIcon icon = new ImageIcon(fileName);
                        JLabel img = new JLabel(icon);
                        mData.add(new PicBean(img , fileName));
                        images.add(img);
                        images.updateUI();
                    }
                }


            }
        });

        btnDel.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int lastPos = mData.size() - 1;
                if(lastPos >= 0 ){
                    PicBean bean = mData.get(lastPos);
                    images.remove(bean.getJpic());
                    images.updateUI();
                    mData.remove(bean);
                }

            }
        });

        btnUpload.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if(mData.size() > 0){
                    int pos = 1;
                    for(PicBean bean : mData){
                        startUpload(bean , pos);
                        pos++;
                    }

                }else {
                    errDialog("没有选择图片");
                }
            }
        });
        add(buttons, BorderLayout.SOUTH);


    }

    private void errDialog(String string){
        JFrame errorDialog = new JFrame();
        errorDialog.getContentPane().add(BorderLayout.CENTER , new JLabel(string));
        errorDialog.setLocationRelativeTo(null);
        errorDialog.setSize(400 , 200);
        errorDialog.setVisible(true);
    }

    private void startUpload(PicBean bean , int pos){
        JFrame dialog = new JFrame();
        dialog.setTitle("图片" + pos + " 上传进度");
        dialog.setSize(400 , 200);
        dialog.setLocationRelativeTo(null);
        JPanel progressPanel = new JPanel();
        JLabel label = new JLabel();
        JProgressBar progressBar = new JProgressBar();
        progressBar.setStringPainted(true);
        progressBar.setMaximum(100);
        new Thread(new Runnable() {
            @Override
            public void run() {
                upLoad(bean , progressBar , label);
            }
        }).start();
        progressPanel.add( BorderLayout.CENTER ,progressBar);


        dialog.add(BorderLayout.SOUTH , label);
        dialog.add(progressPanel);
        dialog.setVisible(true);

    }


    class PicJpanel extends JPanel{
        private Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(screen.width / 10 * 6,
                    screen.height / 10 * 6);
        }
        public PicJpanel(LayoutManager layout) {
            super(layout);
        }
    }


    //图片对象
    class PicBean{
        Component Jpic = null;
        String picPath = null;

        public PicBean(Component jpic, String picPath) {
            Jpic = jpic;
            this.picPath = picPath;
        }

        public Component getJpic() {
            return Jpic;
        }

        public void setJpic(Component jpic) {
            Jpic = jpic;
        }

        public String getPicPath() {
            return picPath;
        }

        public void setPicPath(String picPath) {
            this.picPath = picPath;
        }
    }

    //上传图片业务
    private void upLoad(PicBean bean , JProgressBar progressBar , JLabel label){
        File file = new File(bean.getPicPath());
        final HashMap<String,String> map = new HashMap<String,String>();
        map.put("fromname", "upload");
        map.put("followchatid", "22");
        map.put("nodeid", "127.0.0.1");
        map.put("nodeidport", "8000");
//        map.put("files", bean.getPicPath());

        System.out.println(bean.getPicPath());

        System.out.println("url = " + urlPath);

        System.out.println("file = " + new File(bean.getPicPath()).getName());

        System.out.println(map);

        try{
            FileUploader.upload(urlPath, new File(bean.getPicPath()), map, new FileUploader.FileUploadListener() {
                @Override
                public void onProgress(long pro, double precent) {
                    System.out.println("pro:" + pro + ", precent:" + precent);
                    progressBar.setValue((int) precent);

                }

                @Override
                public void onFinish(int code, String res, Map<String, List<String>> headers) {
                    System.out.println("res " + res);
                    label.setText("上传成功");
                }
            });
        }catch (Exception ex){
            ex.printStackTrace();
        }

    }




}
